//
//  Seqlist.c
//  顺序表(C)
//
//  Created by Yan Zihao on 2024/12/12.
//
#include "Seqlist.h"

void SLInit(SL* ps)
{
    ps->arr = NULL;
    ps->size = ps->capacity = 0;
}

void SLDestory(SL* ps)
{
    free(ps->arr);
    ps->arr = NULL;
    ps->size = ps->capacity = 0;
}

void SLCheckCapacity(SL* ps)
{
    if(ps->capacity == ps->size)
    {
        int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
        SLDataType* tmp = (SLDataType*)realloc(ps->arr, newcapacity * sizeof(SLDataType));
        if(tmp == NULL)
        {
            perror("realloc fail:");
            return;
        }
        ps->arr = tmp;
        ps->capacity = newcapacity;
    }
}

void SLPushBack(SL* ps,SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);
    ps->arr[ps->size++] = x;
}

void SLPushFront(SL* ps,SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);
    for(int i = ps->size;i > 0;i--)
    {
        ps->arr[i] = ps->arr[i-1];
    }
    ps->arr[0] = x;
    ps->size++;
}

void SLPopBack(SL* ps)
{
    assert(ps);
    assert(ps->size > 0);
    ps->size--;
}

void SLPopFront(SL* ps)
{
    assert(ps);
    assert(ps->size > 0);
    for (int i = 0; i <= ps->size - 2; i++)
    {
        ps->arr[i] = ps->arr[i+1];
    }
}

void SLPrint(SL s)
{
    for (int i = 0; i < s.size; i++)
    {
        printf("%d ",s.arr[i]);
    }
    printf("\n");
}
